package com.itheima.edu.info.manager.dao;

import com.itheima.edu.info.manager.domain.Student;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

/*
库管类:
核心职责管理我们的数据仓库--数组或集合
这里的所有方法和功能都是给业务层用
 */
public class OtherStudentDao03 implements BaseStudentDao {
    private static ArrayList<Student> stu = new ArrayList<>();

    static {
        try {
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream("itheima-edu-info-manager\\stu2.txt"));
            stu = (ArrayList<Student>) ois.readObject();
            ois.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean addStudent(Student student) {
        boolean add = stu.add(student);
        reSave();
        return add;
    }


    public Student[] findAllStudent() {
        Student[] stus = new Student[stu.size()];
        Student[] students = stu.toArray(stus);
        return students;
    }

    public void deleteStudent(String delId) {
        int index = getIndex(delId);
        stu.remove(index);
        reSave();
    }

    public int getIndex(String id) {
        int index = -1;
        for (int i = 0; i < stu.size(); i++) {
            Student student = stu.get(i);
            if (student != null && student.getSid().equals(id)) {
                index = i;
            }
        }
        return index;
    }

    public void updateStudent(String updateId, Student newStu) {

        int index = getIndex(updateId);
        stu.set(index, newStu);
        reSave();
    }

    public void reSave() {
        try {
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("itheima-edu-info-manager\\stu2.txt"));
            oos.writeObject(stu);
            oos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
